﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Forms;

namespace WMI
{
    public partial class FrmNetwork : Form
    {
        public FrmNetwork()
        {
            InitializeComponent();
        }

        #region 字段
        /// <summary>
        /// 控件cbxNetworkAdapter选中的Index,用于修改IP地址重新加载再选中
        /// </summary>
        private int selectIndex = 0;

        /// <summary>
        /// 查询到指定状态网络适配器
        /// </summary>
        private AdapaterState state;

        #endregion

        #region Load事件
        private void Form1_Load(object sender, EventArgs e)
        {
            tsBtnUsingNetwork.BackColor = Color.SkyBlue;
            cbxNetworkAdapter.DisplayMember = "Description";
            state = AdapaterState.EthernetWirelessUseing;
            BindAdapters();
        } 
        #endregion

        #region 方法
        /// <summary>
        /// 绑定Wireless,Ehternet类型 UP的配制器
        /// </summary>
        /// <returns></returns>
        private void BindEthernetWirelessAdaptersUP()
        {
            NetworkAdapterUtil util = new NetworkAdapterUtil();
            List<NetworkAdapter> lists = util.GetEthernetWirelessNetworkAdaptersUP(); 
         
            cbxNetworkAdapter.DataSource = lists; //重新绑定数据

            if (cbxNetworkAdapter != null && cbxNetworkAdapter.Items.Count > selectIndex)
            {
                cbxNetworkAdapter.SelectedIndex = selectIndex;
            }
        }

        /// <summary>
        /// 绑定所有适配器
        /// </summary>
        private void  BindAllAdapters()
        {
          
            NetworkAdapterUtil util = new NetworkAdapterUtil();
            List<NetworkAdapter> lists = util.GetAllNetworkAdapters(); //得到所有适配器;

            cbxNetworkAdapter.DataSource = lists; //重新绑定数据

            if (cbxNetworkAdapter != null && cbxNetworkAdapter.Items.Count > selectIndex)
            {
                cbxNetworkAdapter.SelectedIndex = selectIndex;
            }
        }

        /// <summary>
        /// 绑定适配器,会根据state的值绑定
        /// </summary>
        private void  BindAdapters()
        {

            if (state == AdapaterState.All)
            {
                BindAllAdapters();               
            }
            else if (state == AdapaterState.EthernetWirelessUseing)
            {
                BindEthernetWirelessAdaptersUP();
            }
        }
        #endregion

        #region 事件

        private void btnGetIPAddress_Click(object sender, EventArgs e)
        {
            try
            {            
                NetworkAdapter adapter = cbxNetworkAdapter.SelectedItem as NetworkAdapter;
                if (adapter == null) MessageBox.Show("请先选择适配器");
                selectIndex = cbxNetworkAdapter.SelectedIndex; //获取适配器的index,为了重新加载再选上这
           
                string ipAddress = txtIpAddress.Text.Trim(); //IP地址
                string subMask = txtMask.Text.Trim(); //子网掩码           
                string getWay = txtGetway.Text.Trim(); //网关             
                string dnsMain = txtDnsMain.Text.Trim(); //主DNS
                string dnsBackup = txtDnsBackup.Text.Trim(); //备用DNS
                string reslut = adapter.IsIPAddress(ipAddress, subMask, getWay, dnsMain, dnsBackup); //检查输入设置的IP地址，如果返回空，表示成功，否则就失败
                if (!string.IsNullOrEmpty(reslut))
                {
                    MessageBox.Show(reslut);
                    return;
                }

                if (!adapter.SetIPAddressAndSubMask(ipAddress, subMask))//设置IP地址和子网掩码
                {
                    MessageBox.Show("设置IP地址和子网掩码失败");
                    return;
                }

                if (!string.IsNullOrEmpty(getWay))
                {
                    if (!adapter.SetGetWayAddress(getWay)) //设置网关地址
                    {
                        MessageBox.Show("设置网关地址失败");
                        return;
                    }
                }

                if (!string.IsNullOrEmpty(dnsMain))
                {
                    if (!adapter.SetDNSAddress(dnsMain, dnsBackup)) //设置DNS地址;
                    {
                        MessageBox.Show("设置DNS失败");
                        return;
                    }
                }

                MessageBox.Show("设置IP地址成功");
                BindAdapters(); //绑定适配器

            }
            catch (Exception)
            {
                MessageBox.Show("Catch Exception!!!");
            }

        }

        private void btnSetAutoIPAddress_Click(object sender, EventArgs e)
        {
            NetworkAdapter adapter = cbxNetworkAdapter.SelectedItem as NetworkAdapter; //获取到选中的适配器
            if (adapter == null) MessageBox.Show("请先选择适配器");
            selectIndex = cbxNetworkAdapter.SelectedIndex; //控件cbxNetworkAdapter选中的Index,用户重新加载再选中

            if (adapter.EnableDHCP()) //设置自动获取IP地址
            {
                MessageBox.Show("设置自动获取IP成功");
                BindAdapters();////绑定适配器
            }
            else
            {
                MessageBox.Show("设置自动获取IP失败");
            }

        }

        private void cbxNetworkAdapter_SelectedIndexChanged(object sender, EventArgs e)
        {
            NetworkAdapter adapter = cbxNetworkAdapter.SelectedItem as NetworkAdapter; //获取到选中的适配器
            txtIpAddress.Text = adapter.IpAddress;
            txtGetway.Text = adapter.Getway;
            txtMask.Text = adapter.Mask;
            txtPhycilAddress.Text = adapter.MacAddres;
            txtDnsMain.Text = adapter.DnsMain;
            txtDnsBackup.Text = adapter.DnsBackup;
            txtDhcpServer.Text = adapter.DhcpServer;
            if (adapter.IsDhcpEnabled)
            {
                cbxGetIPMethod.SelectedIndex = 0;
            }
            else
            {
                cbxGetIPMethod.SelectedIndex = 1;
            }
          
        }

        //获取所有启用网络适配器地址 事件， 如果网卡是禁用的是获取不到
        private void tsBtnDisplayAllNetwork_Click(object sender, EventArgs e)
        {
            tsBtnUsingNetwork.BackColor = SystemColors.Control;
            tsBtnDisplayAllNetwork.BackColor = Color.SkyBlue;

            state = AdapaterState.All;
            selectIndex = 0;
            BindAdapters();
        }

        //获取正在使用适配器地址 事件
        private void tsBtnUsingNetwork_Click(object sender, EventArgs e)
        {;
            tsBtnUsingNetwork.BackColor = Color.SkyBlue;
            tsBtnDisplayAllNetwork.BackColor = SystemColors.Control;


            state = AdapaterState.EthernetWirelessUseing;
          
            BindAdapters();  //重新获取适配器信息并绑定
        } 
    

        private void tsBtnAllIPReport_Click(object sender, EventArgs e)
        {
           
            FrmReport frmReport = new FrmReport();
            frmReport.Show();
        }


        private void tsBtnEnableAdapters_Click(object sender, EventArgs e)
        {
            try
            {
                new NetworkAdapterUtil().EnableAllAdapters();
                MessageBox.Show("启用所有网络连接成功");
              //  BindAdapters(); //绑定适配器

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void tsBtnDisableAdapters_Click(object sender, EventArgs e)
        {
            try
            {
                new NetworkAdapterUtil().DisableAllAdapters();
                MessageBox.Show("禁用所有网络连接成功");
               // BindAdapters(); //绑定适配器
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        #endregion
    }

    enum AdapaterState
    {
        All,
        EthernetWirelessUseing
    }
}


/*
这么久了，还有分给吗？

 private void button5_Click(object sender, EventArgs e)
        {
            ManagementClass DiskClass;
            using (DiskClass = new ManagementClass(@"Win32_Diskdrive"))
            {
                ManagementObjectCollection Moc = DiskClass.GetInstances();
                foreach (ManagementObject Mo_Disk in Moc)
                {
                    Console.WriteLine(Mo_Disk["Model"]);
                    {
                        foreach (ManagementObject Mo_Partition in   Mo_Disk.GetRelated("Win32_DiskPartition"))
                        {
                            Console.WriteLine("{0}", Mo_Partition["Name"]);
                            foreach (ManagementBaseObject Mbo_Logical in Mo_Partition.GetRelated("Win32_LogicalDisk"))
                            {
                                Console.WriteLine("{0}", Mbo_Logical["Name"]);
                             }
                        }
                    }
                }
            }
        }
输出如下：

WDC WD3200BEVS-08VAT2
磁盘 #0，分区 #0
C:
磁盘 #0，分区 #1
D:
E:
F:
G:
H:
General USB Flash Disk USB Device
磁盘 #1，分区 #0
J:
 * 
 * 
 * 
 * DriveInfo[] drives = DriveInfo.GetDrives();
            foreach (DriveInfo info in drives)
            {
                Console.WriteLine(info.Name);
            }
*/